import logging
from logging.handlers import RotatingFileHandler

from flask import Flask,render_template
from flask import g
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_session import Session
from config import config_dict
redis_store = None
db = SQLAlchemy()


def create_app(env):
    app = Flask(__name__)
    config_classname = config_dict[env]
    app.config.from_object(config_classname)
    log_file(config_classname.LOG_LV)
    db.init_app(app)
    global redis_store
    redis_store = StrictRedis(host=config_classname.REDIS_HOST,port=config_classname.REDIS_PORT)
    Session(app)
    from flask.ext.wtf import CSRFProtect
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        # 生成 csrf_token 随机值
        from flask.ext.wtf.csrf import generate_csrf
        csrf_token = generate_csrf()
        # 将 csrf_token 的值传给前端浏览器（通过设置cookie）
        response.set_cookie("csrf_token", csrf_token)
        return response
    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class,"to_classname")
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from info.modules.news_detail import news_detail_blu
    app.register_blueprint(news_detail_blu)
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)
    from info.utils.common import user_login_data
    @app.errorhandler(404)
    @user_login_data
    def page_not_found(e):
        user = g.user
        data = {"user":user.to_dict()}
        return render_template("news/404.html", data=data)
    return app


def log_file(LV):
    # 设置哪些日志信息等级要被记录
    logging.basicConfig(level=LV)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)
